import pexpect
import thread
import threading

class Log:
    def __init__(self, name, mode="wb", isNext = True):
        if not mode:mode = "wb"
        if name:
            self.f = open(name, mode)
            self.g_mutex = threading.Lock()
            if isNext:
                self.write("<====> Log Start at "+time.ctime()+" <====>")
            else:
                self.write(str(time.ctime())+"  Continue...")
        else:
            self.f = None
            self.g_mutex = None
    def write(self, line):
        if self.f:
            self.g_mutex.acquire()
            self.f.write(str(time.ctime())+"  "+line+"\r\n")
            self.f.flush()
            self.g_mutex.release()
            
    def __del__(self):
        if self.f:
            self.g_mutex.acquire()
            self.f.close()
            self.f = None
            self.g_mutex.release()
    def close(self):
        if self.f:
            self.f.close()
            self.f = None
class Handle:
    def __init__(self):
        self.handles = []
        self.default = [pexpect.EOF, pexpect.TIMEOUT]
    def add(self, host, username, pwd):
        ssh = pexepct.spawn("ssh %s@%s"%(username, host))
        index = ssh.expect(['password:', 'continue connecting (yes/no)'] + self.default)
        if index == 1:
            ssh.sendline("yes")
            index = ssh.expect(['password:'] + self.default)
        if index == 0:
            ssh.sendline(pwd)
            index = ssh.expect(["Last login:", "Permission denied"] + self.default)
            if index == 0:
                ssh.logfile = Log("ssh_%d.log"%len(self.handles), "ab")
                self.handles.append(ssh)
                return True
        return False
    def cmd(self, cmd):
        for handle in self.handles:
            handle.sendline(cmd)
